/**
 * the script takes care of splitting all datafiles into smaller and easier to handle files
 * the output will be stored in the 'outputDirectory' of you 'PathConfiguration.groovy' definiation
 */

import edu.ucdavis.genomics.metabolomics.binbase.connector.references.kegg.KeggSplitter
import edu.ucdavis.genomics.metabolomics.binbase.connector.references.sdf.SDFSplitter
import edu.ucdavis.genomics.metabolomics.binbase.connector.references.hmdb.SplitHMDBFiles

includeTargets << grailsScript("Init")

//configuration file
def config = new ConfigSlurper().parse(new File('grails-app/conf/PathConfiguration.groovy').toURL())

//where to save the temp files
String tempDir = config.outputDirectory

target(main: "this script access all configured and downloaded files and splits them into manageable portions") {


  Thread kegg = new Thread({
    depends(kegg)
  })

  Thread hmdb = new Thread({
    depends(hmdb)
  })

  hmdb.name = "hmdb"
  kegg.name = "kegg"

  //start our threads
  kegg.start()
  hmdb.start()

  //end the threads
  kegg.join()
  hmdb.join()

}


target(kegg: "splits the kegg files into smaller files") {

  String dir = config.files.kegg.rawdata

  File dirOut = new File(tempDir + File.separator + "kegg")
  dirOut.mkdirs()

  File dataFiles = new File(dir)

  dataFiles.listFiles().each {File file ->

    if (!file.isDirectory()) {
      KeggSplitter.split(file, dirOut)
    }
  }

}


target(hmdb: "splits the hmdb file into smaller files") {

  String dir = config.files.hmdb.rawdata

  File dirOut = new File(tempDir + File.separator + "hmdb")
  dirOut.mkdirs()

  File dataFiles = new File(dir)

  println "working on hmdb files"
  dataFiles.listFiles().each {File file ->

    if (!file.isDirectory()) {
      SplitHMDBFiles.split(file, dirOut)
    }
  }

  println "working on hmdb-sdf files"

  dir = config.files.hmdb.sdf

  dirOut = new File(tempDir + File.separator + "hmdb-sdf")
  dirOut.mkdirs()

  dataFiles = new File(dir)

  dataFiles.listFiles().each {File file ->

    if (!file.isDirectory()) {
      SDFSplitter.split(file, dirOut)
    }
  }
}

//define the default target
setDefaultTarget(main)
